const os = require('os')
const http = require('http');
const https = require('https');
const fs = require('fs');
const { URL } = require('url');

module.exports = {
  getIP() {
    //获取本机ip
    let getIPAdress = function () {
      var interfaces = os.networkInterfaces();
      // console.log('', interfaces)
      for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
          var alias = iface[i];
          if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
            return alias.address;
          }
        }
      }
    }
    let ip = getIPAdress();
    console.log('当前机器IP为：' + ip);// 192.168.0.4
    return ip;
  },

  /**
   * 将url解析成json队形
   * @url 如果有不是从location对象中获取的url，可以使用url参数传入url的字符串。
   * 返回一个json对象：
   *  url_：基础的请求地址，没有参数。
   *  其他参数，以键值对形式。
   **/
  urlToJson(url = decodeURIComponent(location.href)) {
    let uu = new URL(url);
    uu.search_ = {};
    if (uu.search) {
      var searchArr = uu.search.substring(1).split("&");
      let s = {};
      for (let index = 0; index < searchArr.length; index++) {
        var s_ = searchArr[index].split("=");
        s[s_[0]] = s_[1]
      }
      uu.search_ = s;
    }
    return uu;
  },

  /**
   * 将一个对象的值拼接成url
   * @obj 要拼接成查询字符串，注意，对象里面的属性值不能是对象类型，如果是对象类型，则会转换成JSON字符串再拼接
   * @pathname 传入的url，可以不传。
   **/
  jsonToUrl(obj = {}, url = decodeURIComponent(location.href)) {
    if (Object.keys(obj).length === 0) return url;
    let oUrl = this.urlToJson(url);
    let AllSearch = { ...oUrl.search_, ...obj };
    let skeys = Object.keys(AllSearch);
    if (skeys.length > 0) {
      let sString = [];
      skeys.forEach(item => { sString.push(item + '=' + AllSearch[item]); })
      return oUrl.origin + oUrl.pathname + '?' + sString.join('&') + oUrl.hash;
    } else {
      return oUrl.origin + oUrl.pathname + oUrl.hash;
    }
  },
  // 从文本中提取出日期
  getDate(dateTimeString) {
    const dateMatch = dateTimeString.match(/\d{2,4}-\d{1,2}-\d{1,2}/);
    const datePart = dateMatch ? dateMatch[0] : null;
    // console.log(datePart); // 输出: "2023-07-09"
    return datePart
  }
}